<?php

namespace app\index\controller;
use think\Controller;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Image;
use EasyWeChat\Message\News;
class Wechat extends Controller{
    use \traits\controller\Jump;
    public function index($username='',$password=''){   
		$options = [
			'debug'  => false,
			'app_id' => config('CorpID'),
			'secret' => config('Secret'),
			'token'  => 'changyuan',
			'log' => [
				'level' => 'debug',
				'file'  => '/tmp/easywechat.log', 
			]
		];
		$app = new Application($options);
		$server = $app->server;
		$server->setMessageHandler(function ($message) {
				switch ($message->MsgType) {
				case 'event'://事件消息...
				    //关注自动回复
				   if($message->Event=='subscribe'){
					   $v=db('zdhf')->where("keyword='huanying'")->find();
					   if($v['type']=='text'){
						  return $v['content'];
					   }elseif($v['type']=='image'){
						  return new Image(['media_id' =>$v['media_id']]);
					   }else{
						  return $this->get_news($v['content']);
					   }
				 }	
					//菜单点击
					if($message->Event=='CLICK'){
						$arr_key=db('zdhf')->where("type='view'")->column('id,keyword');
			   		    $ids='';
						foreach($arr_key as $k=>$v){
							if($message->EventKey==$v){
							   $ids=db('zdhf')->where("id=$k")->value('content');
                               return $this->get_news($ids);
							}
						}
					}
				break;
				case 'text':
				//文字消息...
				   $list=db('zdhf')->select();
				   foreach($list as $v){
					   if($message->Content==$v['keyword']){
						   if($v['type']=='text'){
				              return $v['content'];
						   }elseif($v['type']=='image'){
						      return new Image(['media_id' =>$v['media_id']]);
						   }else{
							  return $this->get_news($v['content']);
						   }
					   }
				   }
				break;
				
				case 'image':
				//图片消息...
				break;
				
				case 'voice':
				//语音消息...
				break;
				
				case 'video':
				//视频消息...
				break;
				
				case 'location':
				//坐标消息...
				break;
				
				case 'link':
				//链接消息...
				break;
				
				// ... 其它消息
				default:
				break;
				}
		});
		$response = $server->serve();
		$response->send();
    }

	

	

		public function get_news($ids='["4"]'){

			 $news=[];

			 foreach(a2j($ids) as $v){

					$show=db('notice_articles')->where("id=$v")->find();

					$news[] = new News([

						'title'       => $show['goods_name'],

						'description' => mb_substr(str_replace('&nbsp;',' ',strip_tags(html_entity_decode($show['goods_description']))),0,48,'utf-8'),

						'url'         => config('SITEROOT').url('notice/mobile/goods',['id'=>$v]), 

						'image'       => 'http://'.$_SERVER['HTTP_HOST'].'/'.$show['thumbnail']

					]);

	

			 }

			 return $news;

		}



}

